//
//  SSEmoticonView.swift
//  weibo
//
//  Created by 邵帅 on 16/7/2.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit


let EmoticonCellWithReuseIdentifier = "emotionCell"

class SSEmoticonView: UIView {

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        setupCollectionView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        
        toolBar.snp_makeConstraints { (make) in
            
            make.left.bottom.right.equalTo(self)
            make.height.equalTo(44)
        }
        
        emoticonCollectionView.snp_makeConstraints { (make) in
            
            make.left.top.right.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
    }
    
    func setupCollectionView() {
        
        emoticonCollectionView.registerClass(SSEmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonCellWithReuseIdentifier)
        
        emoticonCollectionView.dataSource = self
        emoticonCollectionView.delegate = self
        
        emoticonCollectionView.pagingEnabled = true
        emoticonCollectionView.showsVerticalScrollIndicator = false
//        emoticonCollectionView.showsHorizontalScrollIndicator = false
        
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .Horizontal
        
        // 让CollectionView滚到 默认
        // 时机的问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.025)), dispatch_get_main_queue()) { () -> Void in
            
            self.emoticonCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
        
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        flowLayout.itemSize = emoticonCollectionView.bounds.size
    }
    
    // 懒加载控件
    private lazy var toolBar: SSEmoticonToolBar = {
        
        let toolBar = SSEmoticonToolBar(frame: CGRectZero)
        
        toolBar.btnClosure = {(btnType: toolBarType)->() in
            
            switch btnType {
                
            case .Recent: self.emoticonCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
                
            case .Default: self.emoticonCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
                
            case .Emoji: self.emoticonCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 2), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
                
            case .Lxh: self.emoticonCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 3), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
                
            }
        }
        
        
        
        return toolBar
    }()
    
    private lazy var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    private lazy var emoticonCollectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
}

extension SSEmoticonView: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return SSEmoticonManager.getAllEmoticons().count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return SSEmoticonManager.getAllEmoticons()[section].count
    }

    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellWithReuseIdentifier, forIndexPath: indexPath) as! SSEmoticonViewCell
        
        cell.emoticon = SSEmoticonManager.getAllEmoticons()[indexPath.section][indexPath.item]
        
        cell.backgroundColor = RandomColor()
        
        return cell
    }
    
}

// 自定义cell
class SSEmoticonViewCell: UICollectionViewCell {
    
    var emoticon: [SSEmoticon]? {
        
        didSet{
            
            for btn in btnEmoticonArr {
                
                btn.hidden  = true
            }
            
            for (index,emotion) in emoticon!.enumerate() {
                
                let btn = btnEmoticonArr[index]
                
                btn.emoticonButton = emotion
             
                btn.hidden = false
            }
            
            
        }
        
    }
    
    private lazy var btnEmoticonArr: [SSEmoticonBtn] = [SSEmoticonBtn]()
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        addChildBtn()
        
    }
    
    private func addChildBtn() {
        
        // 设置button的宽和高
        let childButtonW: CGFloat = bounds.width / 7
        let childButtonH: CGFloat = bounds.height / 3
        
        for i in 0..<20 {
            
            let btn = SSEmoticonBtn()
            
            btn.frame = CGRectMake(CGFloat(i % 7)*childButtonW, CGFloat(i / 7)*childButtonH, childButtonW, childButtonH)
            
            btn.addTarget(self, action: #selector(SSEmoticonViewCell.btnClick(_:)), forControlEvents: .TouchUpInside)
            
            // 设置button的其他属性
            btn.titleLabel?.font = UIFont.systemFontOfSize(32)
            
            contentView.addSubview(btn)
            
            btnEmoticonArr.append(btn)
            
        }
        
        deleteBtn.frame = CGRectMake(bounds.width - childButtonW, bounds.height - childButtonH, childButtonW, childButtonH)
        
        contentView.addSubview(deleteBtn)
    }
    
    @objc private func btnClick(btn: SSEmoticonBtn) {
        
        guard let emoticon = btn.emoticonButton else {
            return
        }
        
        SSEmoticonManager.addRecentEmoticon(emoticon)
        
        // 发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationShowEmoticon, object: nil, userInfo: ["emoticon": emoticon])
    }
    
    // 删除按钮
    @objc private func deleteBtnClick(deleteBtn: UIButton) {
        
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationDeleteEmoticon, object: nil)
        
        
    }
    
    // 懒加载
    private lazy var deleteBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setImage(UIImage(named:"compose_emotion_delete"), forState: .Normal)
        btn.setImage(UIImage(named:"compose_emotion_delete_highLighted"), forState: .Highlighted)
        
        btn.addTarget(self, action: #selector(SSEmoticonViewCell.deleteBtnClick(_:)), forControlEvents: .TouchUpInside)
        
        return btn
    }()
    
}
